package com.g2room.driving.grap.news;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.eclipse.jetty.util.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.g2room.driving.grap.GenericGrap;
import com.g2room.driving.util.HtmlUtil;
import com.g2room.driving.util.ImageUtil;
import com.g2room.myuall.util.DbUtil;

public class HandleImages {
	public static void main(String[] args) {
//		Map<Integer, String> imageMap = getImgData(null);
//		HandleImages hi = new HandleImages();
//		for(int id : imageMap.keySet())
//		hi.getImgs(id, imageMap.get(id));
		
		
//		new HandleImages().updateJs();
//		new HandleImages().updateWidth();
		new HandleImages().updateSummary();
	}
	
	/**
	 * 去掉js图片轮播
	 */
	private void updateJs() {
		// 从图片获取那些有js轮播
		File file = new File("D:/userdata/imags/1nsh/news/no");
		StringBuffer sb = new StringBuffer();
		for(File f: file.listFiles()) {
			String id = f.getName().replace(".jpg", "");
			if(sb.length() > 0) sb.append(",");
			sb.append(id);
		}
		
		Map<Integer, String> imageMap = getIdAndContent(sb.toString());
		for(int id : imageMap.keySet()) {
			String content = imageMap.get(id);
			if(StringUtil.isNotBlank(content)) {
				content = HtmlUtil.delScriptAndStyleTag(content);
				Document doc = GenericGrap.getDocByHtml(content);
				Element el = doc.getElementsByTag("body").first();
				for(Element child : el.children()) {
					if(child.tagName().equalsIgnoreCase("div")) child.remove();
				}
				content = el.html();
			}
			
			updateContent(id, content);
		}
	}
	
	private void updateWidth() {
		// 从图片获取那些有js轮播
		File file = new File("D:/userdata/imags/1nsh/news/cover");
		List<String> ids = new ArrayList<String>();
		for(File f: file.listFiles()) {
			String id = f.getName().replace(".jpg", "");
			ids.add(id);
			try {
				Image src = ImageIO.read(f);//构造Image对象
				updateWidth(Integer.valueOf(id), id, src.getWidth(null), src.getHeight(null));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取已经抓取的了图片sql，从d_images
	 * @return
	 */
	public static Map<Integer, String> getIdAndContent(String ids) {
		String sql = "select id,content from news_info " + (null == ids ? "" : "where id in ("+ids + ")");
		Map<Integer, String> imgs = new HashMap<Integer, String>();
		try {
			Connection connection = DbUtil.getNewsConn();
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				imgs.put(rs.getInt("id"), rs.getString("content"));
			}
			rs.close();
			statement.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imgs;
	}
	/**
	 * 获取已经抓取的了图片sql，从d_images
	 * @return
	 */
	public void updateContent(int id, String content) {
		PreparedStatement grapPs = null;
		try {
			grapPs = DbUtil.getNewsConn().prepareStatement("update news_info set content=? where id=?");
			grapPs.setString(1, content);
			grapPs.setInt(2, id);
			grapPs.execute();
			grapPs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != grapPs) {
				try {
					grapPs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 获取已经抓取的了图片sql，从d_images
	 * @return
	 */
	public void updateWidth(int id, String url,  int w, int h) {
		PreparedStatement grapPs = null;
		try {
			grapPs = DbUtil.getNewsConn().prepareStatement("update news_info set cover_width=?,cover_height=?, cover=? where id=?");
			grapPs.setInt(1, w);
			grapPs.setInt(2, h);
			grapPs.setString(3, url);
			grapPs.setInt(4, id);
			grapPs.execute();
			grapPs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != grapPs) {
				try {
					grapPs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public void updateSummary() {
		Map<Integer, String> map = getIdAndContent(null);
		PreparedStatement grapPs = null;
		try {
			grapPs = DbUtil.getNewsConn().prepareStatement("update news_info set summary=? where id=?");
			for(int id : map.keySet()) {
				String content = HtmlUtil.delHTMLTag(map.get(id)).trim().replaceAll("　", "");
				grapPs.setString(1, content.substring(0, Math.min(content.length(), 200)));
				grapPs.setInt(2, id);
				grapPs.addBatch();
			}
			grapPs.executeBatch();
			grapPs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != grapPs) {
				try {
					grapPs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 获取已经抓取的了图片sql，从d_images
	 * @return
	 */
	public void updateCover(int id, String url) {
		PreparedStatement grapPs = null;
		try {
			grapPs = DbUtil.getNewsConn().prepareStatement("update news_info set cover=? where id=?");
			grapPs.setString(1, url);
			grapPs.setInt(2, id);
			grapPs.execute();
			grapPs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != grapPs) {
				try {
					grapPs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void getImgs(int id, String content) {
		try {
			List<String> imgUrls = ImageUtil.getImgSrc(content);
			if(null != imgUrls && !imgUrls.isEmpty()) {
//				ImageUtil.downloadImageByType(imgUrls.get(0), id+".jpg");
				updateCover(id, imgUrls.get(0));
//				Map<Integer, Integer> map = ImageUtil.getImgWidth(imgUrls.get(0));
//				for(int key : map.keySet()) {
//					updateWidth(id, imgUrls.get(0), key, map.get(key));
//				}
			}
		} catch (Exception e) {
			System.out.println(id);
			e.printStackTrace();
		}
	}
}
